﻿Ext.require([
    'Twi.Msg',
    'Twi.Tbar',
    'Twi.QuickAjax',
    'Twi.QuickGrid',
    'Twi.QuickPagingGrid',
    'Twi.QuickWin',
    'BIM.store.User',
    'TAB.view.user.UserNewOrEditForm',
    'BIM.store.Option',
    'BIM.store.Tree'
]);

Ext.onReady(function () {
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';
    twiSelf.init();
});

Twi.TAB.UserManage = {

    Vars: {
        userGrid: null,
        leftTab: null,
        dutyGrid: null,
        deptTree: null,
        roleAssignGrid: null,
        userMappingName: 'SM010',
        userViewMappingName: 'SM010-V1',
        treeMappingName: 'SM002',
        optionMappingName: 'SM004',
        dutyOptionTypeID: '846ca4f6-ae5c-4293-be47-332dd5604fc9',
        lastSameName: '' //最后一次判断的存在的重复的用户名值
    } //end Vars

    , init: function () {
        twiVars.leftTab = twiSelf.Tab.createLeftTab();
        twiVars.userGrid = twiSelf.Grid.createUserGrid();
    } //end init;

    , Grid: {
        createUserGrid: function () {
            var store = Ext.create("BIM.store.User");
            store.load();
            store.on('load', function (s) {
                //解决grid.store.load()后，默认选择的行其实是load之前选择的脏数据
                var grid = twiVars.userGrid;
                var lastSltRecord = grid.getSelectionModel().getLastSelected();
                if (lastSltRecord) {
                    grid.getSelectionModel().deselectAll();
                    var sltRecord = s.getById(lastSltRecord.getId());
                    if (sltRecord) {
                        grid.getSelectionModel().select(sltRecord);
                    }
                }
            });
            var actionItems = twiSelf.ActionItems.createUserItems();
            var contextMenu = Ext.create('Ext.menu.Menu', {
                items: actionItems
            });
            var tbarQuery = Twi.Tbar.Query('用户名/姓名：', twiSelf.Fn.User.btnQuery);
            var selModel = Ext.create('Ext.selection.CheckboxModel');
            var grid = Ext.create("Twi.QuickPagingGrid", {
                title: '用户列表',
                forceFit: true,
                store: store,
                renderTo: 'userGrid',
                selModel: selModel,
                resizable: true,
                dockedItems: [{
                    xtype: 'toolbar',
                    items: actionItems.concat('->', tbarQuery)
                }],
                viewConfig: {
                    stripeRows: true,
                    listeners: {
                        itemcontextmenu: function (view, rec, node, index, e) {
                            e.stopEvent();
                            contextMenu.showAt(e.getXY());
                            return false;
                        }
                    }
                },
                columns: [{ xtype: 'rownumberer', width: 30 },
                 {
                     header: '姓名',
                     dataIndex: 'FREALNAME'
                 }, {
                     header: '用户名',
                     dataIndex: 'FNAME'
                 }, {
                     header: '工号',
                     dataIndex: 'FJOBNUMBER'
                 }, {
                     header: '性别',
                     dataIndex: 'FSEX',
                     width: 60
                 }, {
                     header: '手机号',
                     dataIndex: 'FPHONENUMBER'
                 }, {
                     header: '职务',
                     dataIndex: 'FDUTYNAME'
                 }, {
                     header: '状态',
                     dataIndex: 'FISACTIVE',
                     renderer: function (value) {
                         if (value == "1") {
                             return '正常';
                         }
                         else if (value == "0") {
                             return '<span style="color:red;">锁定</span>';
                         }
                         return value;
                     }
                 }, {
                     header: '排序',
                     dataIndex: 'FSORT',
                     width: 60
                 }]
            });

            grid.on('itemdblclick', function () {
                if (!this.dockedItems.items[2].items.items[2].disabled) {
                    this.dockedItems.items[2].items.items[2].handler();
                }
            });

            return grid;

        } //end createUserGrid

       , createDutyGrid: function () {
           var store = Ext.create('BIM.store.Option');
           store.proxy.extraParams.data = Ext.encode({
               TableName: twiVars.optionMappingName,
               OrderFields: 'FSORT',
               Condition:
                {
                    FIsDeleted: 0,
                    FOptionTypeID: twiVars.dutyOptionTypeID
                }
           });
           store.load();
           var actionItems = [Twi.Tbar.Refresh(twiSelf.Fn.Duty.btnRefresh)];
           var tbarQuery = Twi.Tbar.Query('名称：', twiSelf.Fn.Duty.btnQuery);
           var grid = Ext.create("Twi.QuickGrid", {
               //title: '角色列表',
               //forceFit: true,
               store: store,
               //renderTo: 'optionGrid',
               border: false,
               viewConfig: {
                   stripeRows: true
               },
               dockedItems: [{
                   xtype: 'toolbar',
                   items: actionItems.concat('->', tbarQuery)
               }],
               columns: [{ xtype: 'rownumberer', width: 30 },
                 {
                     header: '名称',
                     dataIndex: 'FNAME',
                     flex: 1
                 }, {
                     header: '排序',
                     dataIndex: 'FSORT'

                 }, {
                     header: '备注',
                     dataIndex: 'FREMARK',
                     flex: 1
                 }]
           });
           grid.on('itemclick', function (view, record, item, index, e, eOpts) {
               var data = {
                   TableName: twiVars.userViewMappingName,
                   OrderFields: 'FSORT',
                   Condition:
                    {
                        FIsDeleted: 0,
                        FDutyID: record.data.FID
                    }
               };
               twiVars.userGrid.store.proxy.extraParams.data = Ext.encode(data);
               twiVars.userGrid.store.loadPage(1);
           });
           return grid;

       } //end createDutyGrid

        , createRoleGrid: function () {
            var store = Ext.create("BIM.store.RoleAssign");
            var actionItems = twiSelf.ActionItems.createRoleItems();
            var selModel = Ext.create('Ext.selection.CheckboxModel');
            var grid = Ext.create("Twi.QuickGrid", {
                store: store,
                selModel: selModel,
                dockedItems: [{
                    xtype: 'toolbar',
                    items: actionItems
                }],
                maxHeight: 350,
                viewConfig: {
                    stripeRows: true
                },
                columns: [{
                    xtype: 'rownumberer'
                }, {
                    header: '角色名称',
                    dataIndex: 'FNAME',
                    flex: 1
                }, {
                    header: '是否已分配',
                    dataIndex: 'InAuthority',
                    flex: 1,
                    renderer: function (value) {
                        if (value == "1") {
                            return '<span style="color:blue;">是</span>';
                        }
                        else {
                            return "";
                        }
                    }
                }]
            });
            return grid;

        } //end createRoleGrid
    } //end Grid

    , Tree: {
        createDeptTree: function () {
            //var store = Ext.create('BIM.store.Tree');
            //store.proxy.extraParams.value = '1';
            //store.load();
            var store = Ext.create('Ext.data.TreeStore', {
                fields: ['text', 'level', 'children', 'leaf', 'id', 'parentid', 'code'],
                root:
                {
                    text: '组织结构'
                }
            });
            var actionItems = [Twi.Tbar.Refresh(twiSelf.Fn.Dept.btnRefresh)];
            var tree = Ext.create('Ext.tree.Panel', {
                //title: '树结构详细',
                store: store,
                rootVisible: true,
                height: $(document).height() - Twi.TokenHeight - 3, //自适应高度 
                autoScroll: true,
                useArrows: true,
                dockedItems: [{
                    xtype: 'toolbar',
                    dock: 'top',
                    items: actionItems
                }]
            });
            tree.on('itemclick', function (view, record, item, index, e, eOpts) {
                var data = {
                    TableName: twiVars.userViewMappingName,
                    OrderFields: 'FSORT',
                    Condition:
                    {
                        FIsDeleted: 0
                    }
                };
                if (record.data.leaf) {
                    data.Condition.FDepartmentID = record.data.id;
                }
                else if (record.data.code == '1') {
                    //根节点查询，不需要TreeCondtion      
                }
                else {
                    data.TreeCondition = {
                        Field: 'FDepartmentTCode',
                        Value: record.data.code
                    };
                }
                twiVars.userGrid.store.proxy.extraParams.data = Ext.encode(data);
                twiVars.userGrid.store.loadPage(1);
            });
            Twi.QuickAjax.Ajax({
                params: {
                    cn: 'Tree',
                    mn: 'TAB',
                    mn2: 'GetTreeData',
                    value: '1'
                },
                success: function (twi) {
                    store.setRootNode(twi.data[0]);
                    //tree.expandAll();
                    tree.expandNode(tree.getRootNode());
                }
            });
            //tree.expandAll();
            return tree;
        } //end createDeptTree
    }//end Tree

    , Tab: {
        createLeftTab: function () {
            twiVars.dutyGrid = twiSelf.Grid.createDutyGrid();
            twiVars.deptTree = twiSelf.Tree.createDeptTree();
            var tab = Ext.create('Ext.tab.Panel', {
                renderTo: 'divTab',
                height: $(document).height() - Twi.TokenHeight - 3, //自适应高度 
                //frame: true,
                resizable: true,
                items: [{
                    title: '职务',
                    items: twiVars.dutyGrid
                }, {
                    title: '部门',
                    items: twiVars.deptTree
                }]
            });
            return tab;
        } //end createLeftTab

    } //end Tab

    , Win: {
        createUserWin: function () {
            var form = Ext.create('TAB.view.user.UserNewOrEditForm', { border: false });
            var win = Ext.create('Twi.QuickWin', {
                title: '窗口',
                width: 350,
                //x: 140,
                //y: 100,
                items: [form]
            });
            return { win: win,
                form: form
            }
        } //end createUserWin

        , createRoleAssignWin: function () {
            var grid = twiSelf.Grid.createRoleGrid();
            var win = Ext.create('Ext.window.Window', {
                title: '角色分配',
                width: 400,
                //x: 140,
                //y: 100,
                items: [grid],
                modal: true,
                buttons: [{
                    text: '关闭',
                    handler: function () {
                        this.up('window').close();
                    }
                }]
            });
            return { win: win,
                grid: grid
            }
        } //end createRoleAssignWin

    } //end Win

    , ActionItems: {
        createUserItems: function () {
            var items = Twi.Tbar.CRUD(twiSelf.Fn.User.btnNew, twiSelf.Fn.User.btnEdit, twiSelf.Fn.User.btnDelete, twiSelf.Fn.User.btnRefresh);
            items.push('-', {
                text: '角色分配',
                iconCls: 'ico_logout',
                handler: twiSelf.Fn.User.btnRoleAssign
            });
            return items;
        } //end createUserItems

         , createRoleItems: function () {
             var items = [];
             items.push({
                 text: '角色分配',
                 iconCls: 'ico_add',
                 handler: twiSelf.Fn.Role.btnSetRole
             }, '-', {
                 text: '取消分配',
                 iconCls: 'ico_del',
                 handler: twiSelf.Fn.Role.btnCancelRole
             }, '-', {
                 text: '刷新',
                 iconCls: 'ico_refresh',
                 handler: twiSelf.Fn.Role.btnRefresh
             });
             return items;

         } //end createRoleItems

    } //end ActionItems

    , Fn: {
        User: {
            newOrEditCommit: function (win, newOrEdit) {
                var form = win.form.form;
                var btnCommit = win.win.down('#btnSave');
                btnCommit.clearListeners();
                btnCommit.on('click', function () {
                    if (form.isValid()) {
                        btnCommit.disable();
                        var record = form.getValues();

                        if (twiVars.lastSameName == record.FNAME) {
                            Twi.Msg.Error('', '检测到用户名【' + record.FNAME + '】已经存在，请更换！');
                            btnCommit.enable();
                            return;
                        }

                        record.FSEX = form.findField('FSEX').getValue();
                        record.FISACTIVE = form.findField('FISACTIVE').getValue();
                        record.FDUTYNAME = form.findField('FDUTYID').getRawValue();
                        record.FDEPARTMENTTCODE = form.findField('FDEPARTMENTID').treeCode;
                        var data = {
                            TableName: twiVars.userMappingName,
                            NewOrEdit: newOrEdit,
                            Fields: record,
                            SortModel: {
                                SortField: 'FSort'
                            }
                        };
                        if ("Edit" == newOrEdit) {
                            data.Condition =
                            {
                                FID: record.FID
                            }
                            delete data.Fields.FID;
                        }
                        else {
                            //delete data.Fields.FPWD2;
                            data.Fields.FPWD = "E10ADC3949BA59ABBE56E057F20F883E";
                        }
                        Twi.QuickAjax.Ajax({
                            params: {
                                cn: 'PageCommon',
                                mn: 'TAB',
                                mn2: 'NewOrEdit',
                                data: Ext.encode(data)
                            },
                            success: function (obj) {
                                win.win.close();
                                twiVars.userGrid.store.load();
                            }
                        });
                    }
                });
            } //end newOrEditCommit

            , btnNew: function () {
                var win = twiSelf.Win.createUserWin();
                win.win.setTitle('新增用户[默认密码为123456]');
                twiSelf.Fn.User.newOrEditCommit(win, 'New');
                win.win.show();

                var lastSltNode = twiVars.deptTree.getSelectionModel().getLastSelected();
                if (lastSltNode) {
                    win.form.form.findField('FDEPARTMENTID').setValue(lastSltNode.data.id);
                    win.form.form.findField('FDEPARTMENTID').treeCode = lastSltNode.data.code;
                }
                twiVars.lastSameName = "";
                win.form.form.findField('FNAME').un('change');
                win.form.form.findField('FNAME').on('change', function (field, newValue, oldValue) {
                    Twi.QuickAjax.Ajax({
                        params: {
                            cn: 'PageCommon',
                            mn: 'TAB',
                            mn2: 'ExistField',
                            tableName: 'SM010',
                            fieldName: 'FNAME',
                            fieldValue: field.getValue()
                        },
                        success: function (twi) {
                            if (twi.data) {
                                Twi.Msg.Error('', '检测到用户名【' + field.getValue() + '】已经存在，请更换！');
                                twiVars.lastSameName = field.getValue();
                            }
                        }
                    });
                });

            } //end btnNew

            , btnEdit: function () {
                var lenType = twiVars.userGrid.selModel.selected.length;
                if (lenType > 0) {
                    var win = twiSelf.Win.createUserWin();
                    win.win.setTitle('编辑用户');
                    //win.form.remove(win.form.form.findField("FPWD"));
                    //win.form.remove(win.form.form.findField("FPWD2"));
                    var record = twiVars.userGrid.selModel.selected.items[lenType - 1];
                    win.form.loadRecord(record);
                    twiSelf.Fn.User.newOrEditCommit(win, 'Edit');
                    win.form.form.findField("FDUTYID").store.clearListeners();
                    win.form.form.findField("FDUTYID").store.addListener('load', function (store) {
                        win.form.form.findField("FDUTYID").setValue(record.data.FDUTYID);
                    });
                    win.form.form.findField('FDEPARTMENTID').treeCode = record.data.FDEPARTMENTTCODE;
                    win.win.show();

                    twiVars.lastSameName = "";
                    win.form.form.findField('FNAME').un('change');
                    win.form.form.findField('FNAME').on('change', function (field, newValue, oldValue) {
                        Twi.QuickAjax.Ajax({
                            params: {
                                cn: 'PageCommon',
                                mn: 'TAB',
                                mn2: 'ExistField2',
                                tableName: 'SM010',
                                fieldName: 'FNAME',
                                fieldValue: field.getValue(),
                                id: record.data.FID
                            },
                            success: function (twi) {
                                if (twi.data) {
                                    Twi.Msg.Error('', '检测到用户名【' + field.getValue() + '】已经存在，请更换！');
                                    twiVars.lastSameName = field.getValue();
                                }
                            }
                        });
                    });
                }
                else {
                    Twi.Msg.Info('温馨提示', '请选择一项进行编辑');
                }

            } //end btnEdit

            , btnDelete: function () {
                var len = twiVars.userGrid.selModel.selected.length;
                if (len > 0) {
                    Twi.Msg.Confirm(function () {
                        var IDs = [];
                        Ext.each(twiVars.userGrid.selModel.selected.items, function (item, index, allItems) {
                            IDs.push(item.data.FID);
                        });
                        var data = {
                            TableName: twiVars.userMappingName,
                            IDs: IDs.join(',')
                        };
                        Twi.QuickAjax.Ajax({
                            params: {
                                cn: 'PageCommon',
                                mn: 'TAB',
                                mn2: 'DeleteBySetFlag',
                                data: Ext.encode(data)
                            },
                            success: function () {
                                twiVars.userGrid.store.load();
                            }
                        });
                    });

                }
                else {
                    Twi.Msg.Info('温馨提示', '请选择一项进行删除');
                }
            } //end btnDelete

             , btnRefresh: function () {
                 Ext.ComponentQuery.query('#txtContent', twiVars.userGrid)[0].setValue("");
                 var data = {
                     TableName: twiVars.userViewMappingName,
                     OrderFields: 'FSORT',
                     Condition:
                    {
                        FIsDeleted: 0
                    }
                 };
                 twiVars.userGrid.store.proxy.extraParams.data = Ext.encode(data);
                 twiVars.userGrid.store.loadPage(1);
             } //end btnRefresh

             , btnRoleAssign: function () {
                 var len = twiVars.userGrid.selModel.selected.length;
                 if (len > 0) {
                     if (len > 1) {
                         Twi.Msg.Error('', '出于显示方式综合考虑，暂时只支持一次对一个用户进行角色分配！');
                         return;
                     }
                     var IDs = [];
                     Ext.each(twiVars.userGrid.selModel.selected.items, function (item, index, allItems) {
                         IDs.push(item.data.FID);
                     });
                     var win = twiSelf.Win.createRoleAssignWin();
                     var record = twiVars.userGrid.selModel.selected.items[len - 1];
                     win.win.setTitle("角色分配：" + record.data.FREALNAME);
                     twiVars.roleAssignGrid = win.grid;
                     win.grid.store.proxy.extraParams.userIDs = IDs.join(',');
                     win.grid.store.load();
                     win.win.show();
                 }
                 else {
                     Twi.Msg.Info('温馨提示', '请至少选择一项进行操作');
                 }
             } //end btnRoleAssign

            , btnQuery: function () {
                var content = Ext.ComponentQuery.query('#txtContent', twiVars.userGrid)[0].value;
                if (content) {
                    var data = Ext.decode(twiVars.userGrid.store.proxy.extraParams.data);
                    data.SimpleCondition = {
                        Field: "Names",
                        Value: content,
                        COperator: 'Like'
                    };
                    twiVars.userGrid.store.proxy.extraParams.data = Ext.encode(data);
                    twiVars.userGrid.store.loadPage(1);
                }
                else {
                    twiSelf.Fn.User.btnRefresh();
                }
            } //end btnQuery
        }//end User


        , Duty: {
            btnRefresh: function () {
                Ext.ComponentQuery.query('#txtContent', twiVars.dutyGrid)[0].setValue("");
                var data = {
                    TableName: twiVars.optionMappingName,
                    OrderFields: 'FSORT',
                    Condition:
                    {
                        FIsDeleted: 0,
                        FOptionTypeID: twiVars.dutyOptionTypeID
                    }
                };
                twiVars.dutyGrid.store.proxy.extraParams.data = Ext.encode(data);
                twiVars.dutyGrid.store.load();
            } //end btnRefresh

            , btnQuery: function () {
                var content = Ext.ComponentQuery.query('#txtContent', twiVars.dutyGrid)[0].value;
                var data = {
                    TableName: twiVars.optionMappingName,
                    OrderFields: 'FSORT',
                    Condition:
                    {
                        FIsDeleted: 0,
                        FOptionTypeID: twiVars.dutyOptionTypeID
                    }
                };
                if (content) {
                    data.SimpleCondition = {
                        Field: "FName",
                        Value: content,
                        COperator: 'Like'
                    };
                }
                twiVars.dutyGrid.store.proxy.extraParams.data = Ext.encode(data);
                twiVars.dutyGrid.store.load();
            } //end btnQuery

        } //end Duty

        , Dept:
        {
            btnRefresh: function () {
                //twiVars.deptTree.store.load();
                Twi.QuickAjax.Ajax({
                    params: {
                        cn: 'Tree',
                        mn: 'TAB',
                        mn2: 'GetTreeData',
                        value: '1'
                    },
                    success: function (twi) {
                        twiVars.deptTree.store.setRootNode(twi.data[0]);
                        //twiVars.deptTree.expandAll();
                        twiVars.deptTree.expandNode(twiVars.deptTree.getRootNode());
                    }
                });
            } //end btnRefresh

        } //end Dept

        , Role: {
            btnSetRole: function () {
                var len = twiVars.roleAssignGrid.selModel.selected.length;
                if (len > 0) {
                    var roleIDs = [];
                    var userIDs = [];
                    Ext.each(twiVars.roleAssignGrid.selModel.selected.items, function (item, index, allItems) {
                        roleIDs.push(item.data.FID);
                    });
                    Ext.each(twiVars.userGrid.selModel.selected.items, function (item, index, allItems) {
                        userIDs.push(item.data.FID);
                    });
                    Twi.QuickAjax.Ajax({
                        params: {
                            cn: 'Role',
                            mn: 'TAB',
                            mn2: 'SetRole',
                            userIDs: userIDs,
                            roleIDs: roleIDs
                        },
                        success: function () {
                            twiVars.roleAssignGrid.store.load();
                        }
                    });
                }
                else {
                    Twi.Msg.Info('温馨提示', '请至少选择一项进行操作');
                }
            } //end btnSetRole

            , btnCancelRole: function () {
                var len = twiVars.roleAssignGrid.selModel.selected.length;
                if (len > 0) {
                    var roleIDs = [];
                    var userIDs = [];
                    Ext.each(twiVars.roleAssignGrid.selModel.selected.items, function (item, index, allItems) {
                        roleIDs.push(item.data.FID);
                    });
                    Ext.each(twiVars.userGrid.selModel.selected.items, function (item, index, allItems) {
                        userIDs.push(item.data.FID);
                    });
                    Twi.QuickAjax.Ajax({
                        params: {
                            cn: 'Role',
                            mn: 'TAB',
                            mn2: 'CancelRole',
                            userIDs: userIDs,
                            roleIDs: roleIDs
                        },
                        success: function () {
                            twiVars.roleAssignGrid.store.load();
                        }
                    });
                }
                else {
                    Twi.Msg.Info('温馨提示', '请至少选择一项进行操作');
                }
            } //end btnCancelRole

            , btnRefresh: function () {
                twiVars.roleAssignGrid.store.load();
            } //end btnRefresh

        } //end Role
    } //end Fn

};                      //end Twi.TAB.UserManage

var twiSelf = Twi.TAB.UserManage;
var twiVars = twiSelf.Vars;


